package com.ruoyi.wechart.service.impl;

import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.device.domain.SysAppUser;
import com.ruoyi.device.service.ISysAppUserService;
import com.ruoyi.framework.web.service.SysPermissionService;
import com.ruoyi.system.service.ISysUserService;
import com.ruoyi.wechart.core.WxCore;
import com.ruoyi.wechart.dmain.WxLoginUser;
import com.ruoyi.wechart.service.IWxLoginService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import com.ruoyi.framework.web.service.TokenService;
import org.springframework.stereotype.Service;

/**
 * 微信登录服务实现
 * @auth zhaoly
 * @date 2024-01-25 10:24
 */
@Service
public class WxLoginService implements IWxLoginService {

    @Value("${wechart.userType}")
    private String userType;

    @Autowired
    private WxCore core;

    @Autowired
    private TokenService tokenService;

    @Autowired
    private ISysUserService userService;

    @Autowired
    private SysPermissionService permissionService;

    @Autowired
    private ISysAppUserService registerService;


    /**
     * 微信登录
     * @param code 小程序预登录coce
     * @param userName 学号/工号/手机号
     * @param password 登录密码
     * @return 登录用户
     */
    @Override
    public WxLoginUser login(String code, String userName, String password){

        //请求wx后台通过code请求openid
        String openid = core.getOpenId(code);

        //String openid = code;

        //获取不到openid直接返回
        if(StringUtils.isBlank(openid)){
            return new WxLoginUser(userName, "", -1, "获取openid失败");
        }

        //通过openid查询系统用户
        SysUser sysUser = userService.getUserByOpenid(openid);
        if(sysUser != null){
            return generatorLoginUser(sysUser);
        }

        //通过用户名密码查询系统用户
        sysUser = userService.getUserByName(userName);
        if(sysUser != null){
            if(SecurityUtils.matchesPassword(password, sysUser.getPassword())){
                sysUser.setWxOpenid(openid);
                userService.updateUser(sysUser);
                return generatorLoginUser(sysUser);
            }else{
                return new WxLoginUser(sysUser.getNickName(), sysUser.getDept().getDeptName(), -1, "用户名或密码不正确");
            }
        }else{
            //通过openid查询已注册未审核用户
            SysAppUser registerUser = registerService.getUserByOpenid(openid);
            if(registerUser != null){
                return generatorLoginUser(registerUser);
            }

            //通过用户名密码查询已注册未审核用户
            registerUser = registerService.getUserByName(userName);
            if(registerUser != null){
                if(SecurityUtils.matchesPassword(password, registerUser.getRegPassword())){
                    registerUser.setRegOpenid(openid);
                    registerService.updateSysAppUser(registerUser);
                    return generatorLoginUser(registerUser);
                }else{
                    return new WxLoginUser(registerUser.getRegName(), registerUser.getRegDept(), -1, "用户名或密码不正确");
                }
            }
        }
        return new WxLoginUser(userName, "", -1, "用户名或密码不正确");
    }

    /**
     * 生成微信用户登录参数
     * @param user 系统用户
     * @return
     */
    private WxLoginUser generatorLoginUser(SysUser user){
        if(user.getStatus().equals("1")){
            return new WxLoginUser(user.getNickName(), user.getDept().getDeptName(), 3, "该账号已被停用");
        }else{
            LoginUser loginUser = new LoginUser(user.getUserId(), user.getDeptId(), user, permissionService.getMenuPermission(user));
            String token = tokenService.createToken(loginUser);
            return new WxLoginUser(user.getNickName(), user.getDept().getDeptName(), token);
        }
    }

    /**
     * 生成微信用户登录参数
     * @param user 申请注册用户
     * @return
     */
    private WxLoginUser generatorLoginUser(SysAppUser user){
        if(user.getRegStatus() == 0){
            return new WxLoginUser(user.getRegName(), user.getRegDept(), 1, "已注册，未审核");
        }else if(user.getRegStatus() == 2){
            return new WxLoginUser(user.getRegName(), user.getRegDept(), 2, "审核未通过：" + user.getRegRemark());
        }
        return new WxLoginUser("", "", -1, "用户名或密码不正确");
    }

    /**
     * 新用户注册
     *
     * @param user 新注册用户实例
     * @return 注册结果
     */
    @Override
    public int register(SysAppUser user) {
        user.setCreateTime(DateUtils.getNowDate());
        user.setRegPassword(SecurityUtils.encryptPassword(user.getRegPassword()));
        return registerService.insertSysAppUser(user);
    }


}